<template>
    <div class="editaddr">
        <van-nav-bar :title="route.query.id ? '编辑地址' : '新增地址'" left-arrow @click-left="onClickLeft" />

        <van-address-edit
            :area-list="areaList"
            :address-info="AddressInfo.content"
            show-delete
            show-set-default
            show-search-result
            :area-columns-placeholder="['请选择', '请选择', '请选择']"
            @save="onSave"
            @delete="onDelete"
        />
    </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { editAddress, removeAddress, getAddr } from "../../api/index";
import { showToast } from "vant";
import { areaList } from "@vant/area-data";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

const onClickLeft = () => history.back();

const onSave = (info) => {
    // let address_detail = info.province + info.county + info.city + info.county + info.addressDetail;
    // console.log(info);
    // let address_name = info.name;
    // let address_phone = info.tel;
    // console.log(address_name);
    // console.log(address_phone);
    // console.log(address_detail);
    let data = {
        address_id: route.query.id,
        address_name: info.name,
        address_phone: info.tel,
        address_province: info.province,
        address_city: info.city,
        address_county: info.county,
        address_detail: info.addressDetail,
    };
    console.log("data==>", data);
    editAddress(data).then((res) => {
        showToast(res.msg);
    });
};

let AddressInfo = reactive({
    content: {},
});

if (route.query.id) {
    getAddr({ address_id: route.query.id }).then((res) => {
        // console.log("1.0", res);
        if (res.code == 200) {
            // console.log("2.0", res.content);
            AddressInfo.content = {
                name: res.content[0].address_name,
                tel: res.content[0].address_phone,
                province: res.content[0].address_province,
                city: res.content[0].address_city,
                county: res.content[0].address_county,
                addressDetail: res.content[0].address_detail,
                isDefault: 0,
            };
            // console.log("1.0", AddressInfo.content);
        }
    });
}

const onDelete = () => {
    let address_id = route.query.id;
    if (address_id) {
        removeAddress({ address_id }).then((res) => {
            // console.log(res);
            showToast(res.msg);
            history.back();
        });
    } else {
        showToast("无法删除");
    }
};
</script>

<style lang="scss" scoped>
:deep(.van-nav-bar) {
    background: #353535;
}
:deep(.van-nav-bar__title) {
    color: #fff;
    font-weight: normal;
}
:deep(.van-nav-bar .van-icon) {
    color: #fff;
}
:deep(.van-button--primary) {
    background: #353535;
    border-color: #353535;
}
</style>
